package com.thti.mecool.client.activity;

import java.util.HashMap;
import java.util.Iterator;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.command.send.work.WorkProjectSend;
import com.thti.mecool.client.command.send.work.WorkmemoSend;
import com.thti.mecool.client.model.biz.WorkmemoBizImpl;
import com.thti.mecool.client.protocol.work.AddWorkmemo;
import com.thti.mecool.client.protocol.work.UpWorkmemo;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.AlterDialogWidget;
import com.thti.mecool.client.widget.IsOKListener;
import com.thti.mecool.client.widget.ProgressDialogWidget;
import com.thti.mecool.client.widget.Toolbar;

public class AddWorkMemoActivity extends BaseActivity {
	private boolean TaskExcuteFlag=false;
	private LinearLayout selectShop;
	private EditText content;
	private Button save, cancel;
	private TextView ShopText;
	private String[] curShopArray;
	private String[] curShopCode;
	private String storeName, storeCode, curCommId;
	private ProgressDialogWidget pd;
	private HashMap<String, String> channelDtos;
	private AlterDialogWidget shopDialog;
	private boolean WorkMemoEdit;
	private WorkmemoBizImpl workmemoBizImpl;
	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if (getDataFlag(HandlerConstant.MemoAddCommand)) {
				if (pd.isShowing())
					pd.dismiss(getCurrentMesg().getContent());
					setResult(10);
				removeDataFlag(HandlerConstant.MemoAddCommand);
				handler.removeCallbacks(runnable);
				finish();
			} else if (getDataFlag(HandlerConstant.getChannelCommand)) {
				channelDtos = workmemoBizImpl.findChannelAll();
				removeDataFlag(HandlerConstant.getChannelCommand);
				handler.sendEmptyMessage(HandlerConstant.WORKMEMOSHOPNAMEINIT);
				handler.removeCallbacks(runnable);
			} else if(getDataFlag(HandlerConstant.MemoEditCommand)){
				if (pd.isShowing())
					pd.dismiss(getCurrentMesg().getContent());
					setResult(10);
				removeDataFlag(HandlerConstant.MemoEditCommand);
				handler.removeCallbacks(runnable);
				finish();
			}else{
				if (getDataFlag(HandlerConstant.CommandFail)) {
					if (pd.isShowing())
						pd.dismiss();
//					Util.sendToast(AddWorkMemoActivitythis, "失败");
					Util.sendToast(AddWorkMemoActivity.this, getCurrentMesg().getContent());
					removeDataFlag(HandlerConstant.CommandFail);
					handler.removeCallbacks(runnable);
				} else
					handler.postDelayed(runnable, 1000);
			}
		}
	};

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HandlerConstant.GETWORKMEMOMSG:
				post(runnable);
				break;
			/**
			 * 将hashmap转换成数组
			 */
			case HandlerConstant.WORKMEMOSHOPNAMEINIT:
				convertArr(channelDtos);
				if (pd.isShowing()) {
					pd.dismiss("获取门店地址成功！");
				}
				break;
			}
		};
	};
private void convertArr(HashMap<String,String> channelDtos){
	curShopArray = new String[channelDtos.size() + 1];
	curShopCode = new String[channelDtos.size() + 1];
	int i = 1;
	curShopArray[0] = "无门店";
	curShopCode[0] = "-1";
	for (Iterator<String> it = channelDtos.keySet().iterator(); it
			.hasNext();) {
		String key = it.next();
		curShopCode[i] = key;
		curShopArray[i] = channelDtos.get(key);
		i++;
	}
}
	/**
	 * 
	 * @param channelCode
	 * @param flag
	 *            flag==1时 添加备忘 flag==2时 编辑备忘
	 */
	private void WorkMemoSend(String channelCode, int flag) {
		switch (flag) {
		case 1:
			AddWorkmemo addWorkmemo = new AddWorkmemo();
			addWorkmemo.setContent(content.getText().toString());
			addWorkmemo.setChannelCode(channelCode);
			addWorkmemo.setUserId(String.valueOf(getCurrentUser().getId()));
			WorkmemoSend.addWorkmemo(addWorkmemo);
			break;
		case 2:
			UpWorkmemo upWorkmemo = new UpWorkmemo();
			upWorkmemo.setChannelCode(channelCode);
			upWorkmemo.setUserId(String.valueOf(getCurrentUser().getId()));
			upWorkmemo.setContent(content.getText().toString());
			upWorkmemo.setMemoId(curCommId);
			WorkmemoSend.updateWorkmemo(upWorkmemo);
			break;
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getKeyCode()==KeyEvent.KEYCODE_BACK)
			setResult(10);
		return super.onKeyDown(keyCode, event);
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		setCurrentMesg(null);
	};

	/**
	 * 判断storeCode是否为空
	 */
	public boolean judge(int which) {
		if (!TaskExcuteFlag) {
			if (!WorkMemoEdit) {
				if (which == -1) {
					Util.sendToast(this, "请选择终端！");
					return false;
				} else {
					return true;
				}
			}
		}
		return true;
	}

	private OnClickListener MemoListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_add_workmemo_save:
				if (judge(shopDialog.getWhich())) {
					if(pd!=null&!pd.isShowing())
						pd.show();
					if (WorkMemoEdit) {
						WorkMemoSend(storeCode, 2);
					} else {
						WorkMemoSend(storeCode, 1);
					}
					handler.post(runnable);
				}
				break;
			case R.id.mecool_add_workmemo_select_shop:
				shopDialog.setTitle("选择所在门店");
				shopDialog.setItems(curShopArray);
				shopDialog.setReturnView(ShopText);
				shopDialog.setIsOKListener(new IsOKListener() {
					@Override
					public void isOk(boolean isPutOk, String content) {
						if(isPutOk)
							storeCode=curShopCode[shopDialog.getWhich()];
					}
				});
				shopDialog.show();
				break;
			default:
				setResult(10);
				finish();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.noTitle();
		setContentView(R.layout.mecool_add_workmemo);
		Cache.add(this);
		initToolbar();
		workmemoBizImpl = new WorkmemoBizImpl(this);
		channelDtos=new HashMap<String, String>();
		channelDtos.putAll(workmemoBizImpl.findChannelAll());
		convertArr(channelDtos);
		
		Intent i = getIntent();
		storeCode = i.getStringExtra("storeCode");
		storeName = i.getStringExtra("storeName");
		TaskExcuteFlag = i.getBooleanExtra("TaskExcuteFlag", false);
		shopDialog = new AlterDialogWidget(AddWorkMemoActivity.this);
		ShopText = (TextView) findViewById(R.id.mecool_workmemo_ShopText);
		content = (EditText) findViewById(R.id.mecool_add_workmemo_content);
		cancel = (Button) findViewById(R.id.mecool_add_workmemo_cancel);
		save = (Button) findViewById(R.id.mecool_add_workmemo_save);
		save.setOnClickListener(MemoListener);
		cancel.setOnClickListener(MemoListener);
		pd = new ProgressDialogWidget(this,false);
		if (TaskExcuteFlag) {
			ShopText.setText(storeName);
			ShopText.setEnabled(false);
		} else {
			curCommId = i.getStringExtra("curCommId");
			WorkMemoEdit = i.getBooleanExtra("WorkMemoEdit", false);
			content.setText(i.getStringExtra("workmemocontent"));
			ShopText.setText(i.getStringExtra("workmemoshop"));
			pd.show();
			WorkProjectSend.getProject(getCurrentUser().getLoginName());
			selectShop = (LinearLayout) findViewById(R.id.mecool_add_workmemo_select_shop);
			selectShop.setOnClickListener(MemoListener);
			handler.post(runnable);
		}
	}

	public void initToolbar() {
		Toolbar toolbar = new Toolbar(this);
		Toolbar.hideRightButton();
		toolbar.setToolbarCentreText("添加备忘");
		Toolbar.left_btn.setOnClickListener(MemoListener);
		Toolbar.left_btn.setImageResource(R.drawable.mecool_go_back);
	}
}
